package com.carrie.config.handler;

import com.alibaba.fastjson2.JSON;
import com.carrie.tools.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * @author XuHaiLong
 * @since 2025/4/15 12:45
 */
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        System.out.println(">>>>>>>>>>>>>>>>>>>"+request.getRequestURI());
        String errorMessage = null;
        if (authException instanceof InsufficientAuthenticationException) {
           errorMessage = "请先登录以访问此资源";
        }else if (authException instanceof BadCredentialsException) {
            errorMessage = authException.getMessage();
        }
        response.setContentType("application/json;charset=utf-8");//响应头
        response.getWriter().println(JSON.toJSONString(new Result(401,errorMessage)));
        response.getWriter().flush();
        }
    }